import { Router } from 'express';
import searchService from '../service/DatabaseService.mjs';
import crawlService from '../service/CrawlService.mjs';
import AiModelUtils from '../utils/chat.mjs';
import { parse } from 'url'; //node 内置模块 解析url

const router = Router();

//解决跨域问题
router.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});



function Result(code, data, msg) {
    return {
        code: code,
        data: data,
        msg: msg
    }
}


router.get('/search', async (req, res) => {
    let results = await searchService.searchDataFromDB();
    if (!results) {
        return res.send(Result(0, [], '获取失败'));
    }
    res.set('Content-Type', 'application/json');
    res.send(Result(200, results, '请求成功'));
});



router.get('/crawl', async (req, res) => {
    let results = await crawlService.searchDataFromWeb();
    if (!results) {
        return res.send(Result(0, [], '获取失败'));
    }
    res.set('Content-Type', 'application/json');
    res.send(Result(200, results, '请求成功'));
});


router.get('/chat', async (req, res) => {
    const parsedUrl = parse(req.url, true);
    const queryObj = parsedUrl.query;
    let data = queryObj.data;
    let question = queryObj.question;
    let results = await AiModelUtils.chat(question, data);
    if (!results) {
        return res.send(Result(0, [], '获取失败'));
    }
    res.set('Content-Type', 'application/json');
    res.send(Result(200, results, '请求成功'));
});



export default router;